// 数据表格
const list = document.querySelector('.list')
// 获取UID
const UID = localStorage.getItem('UID')
// 表格控制栏
const first = document.querySelector('.first')
const last = document.querySelector('.last')
const next = document.querySelector('.next')
const theLast = document.querySelector('.theLast')
const paged = document.querySelector('.paged')
const pageSum = document.querySelector('.controlTable select')
const allPage = document.querySelector('.allPage')

// 记录学生学历
let degree

async function getDegree() {
  degree = (await axios({
    url: 'http://127.0.0.1:8080/Student/Elective/getDegree',
    params: {
      UID
    }
  })).data.data
}

getDegree()

// 页码
let page = 1
let pageNumber = 5
// 记录最大页数
let maxPage = 0

// 获取总页数
async function getPageSum() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Student/Elective/getAllCoursePage',
    params: {
      pageNumber
    }
  })).data.data
  maxPage = allPage.innerHTML = result
}

getPageSum()

// 获取所有课程
async function getAllCourse() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Student/Elective/getAllCourse',
    params: {
      page,
      pageNumber
    }
  })).data.data
  const htmlStr = await Promise.all(result.map(async (e) => {
    // 获取教师名字
    const name = (await axios({
      url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getTeacherNameById',
      params: {
        UID: e.teacher
      }
    })).data.data
    const degreeValueArr = e.degreeDemand
    let degreeArr = ''
    for (let i = 0; i < degreeValueArr.length; i++) {
      const degree = degreeValueArr[i]
      if (degree.indexOf("1") !== -1) {
        degreeArr += ' 专科'
      } else if (degree.indexOf("2") !== -1) {
        degreeArr += ' 本科'
      } else if (degree.indexOf("3") !== -1) {
        degreeArr += ' 硕士研究生'
      } else if (degree.indexOf("4") !== -1) {
        degreeArr += ' 博士研究生'
      } else if (degree.indexOf("5") !== -1) {
        degreeArr += ' 博士后研究生'
      }
    }
    return `
      <tr data-id=${e.id}>
        <td>${e.id}</td>
        <td>${e.name}</td>
        <td>${e.credit}</td>
        <td>${name}</td>
        <td>${e.day}</td>
        <td>${e.time}</td>
        <td>${e.location}</td>
        <td>${e.constantTime}</td>
        <td>${e.instructionalMethod}</td>
        <td class="degreeBox">${degreeArr}</td>
        <td>${e.peopleNumber}/${e.peopleSum}</td>
        <td>
          <button class="selectCourse" data-id="${e.id}">选课</button>
        </td>
      </tr>
    `
  }))
  list.innerHTML = htmlStr.join('')
}

// 获取已选课列表
async function getHaveSelectCourse() {
  await getAllCourse()      // 获取全部课程
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Student/Elective/getHaveSelectCourse',
    params: {
      UID
    }
  })).data.data
  console.log(result);
  for (let i = 0; i < result.length; i++) {
    const selectDOM = document.querySelector(`.selectCourse[data-id="${result[i]}"]`)
    selectDOM.classList.add('redColor')
    selectDOM.innerHTML = '退选'
  }
}

getHaveSelectCourse()   // 获取全部课程并选课

async function degreeWithCourse(degree, classId) {
  const degreeDemand = (await axios({
    url: 'http://127.0.0.1:8080/Student/Elective/getCourseDegreeDemand',
    params: {
      classId
    }
  })).data.data
  return degreeDemand.indexOf(degree) === -1
}


// 选课和退选
list.addEventListener('click', async (e) => {
  const element = e.target
  if (!element.classList.contains('selectCourse')) {
    return
  }
  const classId = document.querySelector(`tr[data-id="${element.dataset.id}"] td`).innerHTML    // 点击的课程
  // 获取课程的已选人数和总人数
  let peopleNumAndSum
  try {
    peopleNumAndSum = (await axios({
      url: 'http://127.0.0.1:8080/Student/Elective/peopleNumAndSum',
      params: {
        classId
      }
    })).data.data
  } catch {
    alert('服务器繁忙')
  }
  const peopleNumber = +peopleNumAndSum.peopleNumber
  const peopleSum = +peopleNumAndSum.peopleSum
  if (!element.classList.contains('redColor')) {
    if (peopleNumber >= peopleSum) {
      alert('课程人数已满')
      return
    }
    if (await degreeWithCourse(degree + '', classId)) {
      alert('学历不符合本门课程要求')
      return
    }
    // 给学生添加课程
    await axios({
      url: 'http://127.0.0.1:8080/Student/Elective/addNewCourse',
      method: 'POST',
      params: {
        UID,
        classId
      }
    })
    // 更新课程人数
    axios({
      url: 'http://127.0.0.1:8080/Student/Elective/updateCoursePeopleNumber',
      method: 'POST',
      params: {
        classId,
        peopleNumber: peopleNumber + 1
      }
    }).then(async () => {
      // getAllCourse之后，element是原来的节点，跟新渲染的节点无关系，所以要根据dataset重新去找
      await getAllCourse()    //等待异步操作完成
      await getHaveSelectCourse()
      const newDOM = document.querySelector(`tr[data-id="${element.dataset.id}"] td button`)  //获取新渲染点击的节点
      newDOM.classList.add('redColor')
      newDOM.innerHTML = '退选'
    })
  } else {
    const isDelete = confirm(`确认退选课程号为${classId}的课程`)
    if (!isDelete) {
      return
    }
    // 给学生删除课程
    axios({
      url: 'http://127.0.0.1:8080/Student/Elective/deleteCourse',
      method: 'POST',
      params: {
        UID,
        classId
      }
    })
    // 更新课程人数
    axios({
      url: 'http://127.0.0.1:8080/Student/Elective/updateCoursePeopleNumber',
      method: 'POST',
      params: {
        classId,
        peopleNumber: peopleNumber - 1
      }
    }).then(async () => {
      await getAllCourse()
      await getHaveSelectCourse()
      const newDOM = document.querySelector(`tr[data-id="${element.dataset.id}"] td button`)
      newDOM.classList.remove('redColor')
      newDOM.innerHTML = '选课'
    })
  }
})



// 表格控件监听
first.addEventListener('click', () => {
  page = 1
  getAllCourse()
  getHaveSelectCourse()
})

last.addEventListener('click', () => {
  if (page > 1) {
    --page
    getAllCourse()
    getHaveSelectCourse()
  }
})

next.addEventListener('click', () => {
  getPageSum()
  if (page < maxPage) {
    ++page
    getAllCourse()
    getHaveSelectCourse()
  }
})

theLast.addEventListener('click', () => {
  page = maxPage
  getAllCourse()
  getHaveSelectCourse()
})

pageSum.addEventListener('change', () => {
  pageNumber = pageSum.value
  page = 1
  getAllCourse()
  getHaveSelectCourse()
  getPageSum()
})

paged.addEventListener('change', () => {
  page = paged.value
  // 限定page范围
  page = page > maxPage ? maxPage : page
  page = page < 1 ? 1 : page
  getAllCourse()
  getHaveSelectCourse()
})